package com.example.airhockeytextured.program

import android.content.Context
import android.opengl.GLES20
import android.opengl.GLES20.*

/**
 * @author Liujianyou
 * @date 2020/8/6
 * @des
 */
class TextureShaderProgram(
    context: Context,
    vertexShaderResourceId: String,
    fragmentShaderResourcesId: String
) : ShaderProgram(context, vertexShaderResourceId, fragmentShaderResourcesId) {
    private val uMatrixLocation: Int
    private val uTextureUnitLocation: Int
    private val aPositionLocation: Int
    private val aTextureCoordinatesLocation: Int

    init {
        uMatrixLocation = glGetUniformLocation(program, U_MATRIX)
        uTextureUnitLocation = glGetUniformLocation(program, U_TEXTURE_UNIT)
        aPositionLocation = glGetAttribLocation(program, A_POSITION)
        aTextureCoordinatesLocation = glGetAttribLocation(
            program,
            A_TEXTURE_COORDINATES
        )
    }


    fun setUniforms(matrix: FloatArray, textureId: Int) {
        //第一步传递矩阵给着色器程序的uniform
        glUniformMatrix4fv(uMatrixLocation, 1, false, matrix, 0)
        /* 当我们在OpenGL中使用纹理进行绘制时，我们不需要直接给着色器传递纹理
         我们使用纹理单元保存那个纹理
         通过调用glActiveTexture把活动的纹理单元设置为纹理单元0 我们从此开始，
         然后用过调用glBinTexture 把纹理绑定到这个单元，接着通过调用glUniform1i把
         被选定的纹理单元传递给片段着色器中的u_TextureUnit
         */
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, textureId)
        glUniform1i(uTextureUnitLocation, 0)
    }

    fun getPositionAttributeLocation(): Int {
        return aPositionLocation
    }

    fun getTextureCoordinatesAttributeLocation(): Int {
        return aTextureCoordinatesLocation
    }
}